package com.chongyahhh.security.advice;

import com.chongyahhh.security.bean.model.BaseResult;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolationException;

import static com.chongyahhh.security.util.ConstUtil.VALID_ERROR;


/**
 * 这个类使用来接收 jsr 303 校验参数规范时校验不通过所抛出的异常的，抓取这些异常并统一进行返回
 */

@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice(basePackages = "com.chongyahhh.security.controller")
public class ValidationExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public BaseResult<String> catchValidException(MethodArgumentNotValidException e){
        BaseResult<String> result = new BaseResult<>();
        System.out.println(e.getMessage());
        result.construct(VALID_ERROR,false);
        return result;
    }

    @ResponseBody
    @ExceptionHandler(ConstraintViolationException.class)
    public BaseResult<String> validationParamExceptionHandler(ConstraintViolationException e){
        BaseResult<String> result = new BaseResult<>();
        System.out.println(e.getMessage());
        result.construct(VALID_ERROR,false,null);
        return result;
    }
}
